package kr.co.handysoft.smartPolice.server;

import java.io.File;
import java.io.FilenameFilter;
import java.net.Socket;
import java.util.List;

import kr.co.handysoft.common.registry.SmartPoliceRegistry;

import org.jdom.Element;

public class WatchingFileThread extends Thread {
	
	private Element directoryInfo;
	private Socket socket;
	private String name;
	private String zone;
	private String success;
	private String fail;
	private String server;
	private FileInformationSenderHandler handler;
	private String part;
	private List<Element> doc;

	public WatchingFileThread(Element directoryInformation){

		this.directoryInfo = directoryInformation;
		this.socket = SmartPoliceRegistry.getSocket();
		
		handler = new FileInformationSenderHandler(this.socket, this.directoryInfo);
		handler.setSystemId(this.directoryInfo.getAttributeValue("zone"), this.directoryInfo.getAttributeValue("kor"));
		setup();
		
		SmartPoliceRegistry.setRunState(this.part, true);
	}

	private void setup() {
		this.name = this.directoryInfo.getAttributeValue("name");
		this.zone = this.directoryInfo.getAttributeValue("zone");
		this.success = this.directoryInfo.getAttributeValue("success");
		this.fail = this.directoryInfo.getAttributeValue("fail");
		this.server = this.directoryInfo.getAttributeValue("server"); 
		this.part = this.directoryInfo.getAttributeValue("part"); 
	}

	@Override
	public void run() {
		super.run();
		System.out.println("SmartPoliceRegistry.clientRunStat : " + SmartPoliceRegistry.clientRunStat);
		while(SmartPoliceRegistry.clientRunStat){
			if (SmartPoliceRegistry.getRunState(this.part)){
				invokeWatcher();
			}
				
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void invokeWatcher() {
		
		File watchFolder = new File(this.name + "/" + this.part);
		File[] fileList = watchFolder.listFiles(new FilenameFilter(){
			@Override
			public boolean accept(File dir, String name) {
				if (name.toLowerCase().endsWith(".jpg")){
					return true;
				}else{
					return false;
				}
			}
			
		});
				
		this.handler.invoke(fileList, this.success, this.fail, this.part, "files");
	}


}
